#!/bin/bash

set -e

# 设置默认值
: "${APP_HOME:=/opt/idcops}"
: "${STATIC_ROOT:=${APP_HOME}/static}"
: "${MEDIA_ROOT:=${APP_HOME}/media}"
: "${LOGS_ROOT:=${APP_HOME}/logs}"
: "${DATA_ROOT:=${APP_HOME}/db-data}"
: "${WAL_ROOT:=${APP_HOME}/wal-data}"
: "${PG_DATA_ROOT:=${APP_HOME}/pg-data}"
: "${RUN_ROOT:=${APP_HOME}/run}"
: "${GUNICORN_CONFIG:=${APP_HOME}/contrib/gunicorn.py}"
: "${DB_HOST:=postgres}"
: "${DB_PORT:=3306}"
: "${PG_PORT:=5432}"
: "${NGINX_HOST:=0.0.0.0}"
: "${NGINX_PORT:=80}"
: "${APP_URL:=http://${NGINX_HOST}:${NGINX_PORT}}"

# 等待数据库就绪
wait_for_db() {
    echo "等待 PostgreSQL 数据库就绪..."
    while ! nc -z ${DB_HOST} ${PG_PORT}; do
        sleep 1
    done
    echo "PostgreSQL 数据库已就绪"
}

# 初始化函数
initialize() {
    echo "首次运行，开始初始化..."

    # 创建必要的目录
    mkdir -p ${STATIC_ROOT} ${MEDIA_ROOT} ${LOGS_ROOT} ${DATA_ROOT} ${RUN_ROOT} ${WAL_ROOT} ${PG_DATA_ROOT}

    # 设置目录权限
    chmod -R 755 ${STATIC_ROOT}
    chmod -R 775 ${MEDIA_ROOT}
    chmod -R 755 ${LOGS_ROOT}
    chmod -R 775 ${DATA_ROOT}
    chmod -R 775 ${RUN_ROOT}

    wait_for_db

    # 数据库迁移
    python manage.py collectstatic --no-input
    python manage.py makemigrations
    python manage.py migrate --noinput --verbosity 3

    # 获取容器IP地址
    CONTAINER_IP=$(hostname -i 2>/dev/null || ip route get 1 | awk '{print $NF;exit}' 2>/dev/null || echo "无法获取IP")

    # 记录信息到 install.log 文件
    echo "安装时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "容器IP地址: $CONTAINER_IP"
    echo "管理员用户名: admin"
    echo "管理员密码: $ADMIN_PASSWORD"
    echo "访问地址: ${APP_URL}"
    
    # 创建安装锁定文件
    touch ${APP_HOME}/install.lock
    
    echo "初始化完成"
}

# 检查是否是 web 服务
is_web_service() {
    [ -z "$*" ] || [ "$*" = "/entrypoint.sh" ]
}

# 主逻辑
if is_web_service "$@" && [ ! -f "${APP_HOME}/install.lock" ]; then
    initialize
elif is_web_service "$@"; then
    echo "检测到 install.lock 文件，跳过初始化步骤"
    # 仅执行数据库迁移
    python manage.py migrate --noinput
fi

# 如果是 rq-worker，直接执行命令
if [[ "$*" == *"rqworker"* ]]; then
    echo "启动 RQ Worker..."
    exec "$@"
fi

# 如果是 web 服务，启动 Gunicorn
if is_web_service "$@"; then
    echo "启动 Gunicorn 服务器..."
    echo "监听地址: ${GUNICORN_HOST:-127.0.0.1}:${GUNICORN_PORT:-8000}"
    exec gunicorn idcops.wsgi:application --config ${GUNICORN_CONFIG}
fi